const koaBody = require('koa-body');
const koaCors = require('@koa/cors');
const koaStatic = require('koa-static');
const koaRouter = require('koa-router');
const path = require('path')

const oa = require('./oa/oa')
const admin = require('./admin/admin');
const logger = require('../utils/logger');

function initHttp(app) {
    app.use(koaCors());
    const staticPath = path.join(__dirname, '../static')
    global.staticPath = staticPath;
    app.use(koaBody({ formidable: { 
        maxFileSize: 200 * 1024 * 1024,
        uploadDir: path.join(__dirname, '../static'),
        keepExtensions: true,
        onFileBegin(name, file){
            let originInfo = path.parse(file.originalFilename);
            let pathInfo = path.parse(file.filepath);
            let ext = originInfo.ext;
            let filename = originInfo.name;
            let dirName = pathInfo.dir;
            let newName = filename + '-' + Date.now() + ext;
            file.filepath = path.join(dirName, newName);
            logger.info('上传文件', file.path);
        },
        onError(err){ logger.error('上传文件错误', err); }
    }, multipart: true }))
    app.use(koaStatic(staticPath));

    const router = new koaRouter()

    oa.initOa(router)
    admin.initAdmin(router)

    app.use(router.routes())
}

module.exports = {
    initHttp
}